<template>
  <base-content>
    <template>
      <el-row :gutter="20" class="header">
        <el-col :span="2">账号类型</el-col>
        <el-col v-for="(item, idx) in list[0]" :key="idx" :span="2">{{ item.menu_name }}</el-col>
      </el-row>
      <el-row v-for="(menus, index) in list" :key="index" :gutter="20">
        <el-col :span="2" :class="{'mt': index === 0}">{{ system[menus[index].account_type] }}</el-col>
        <el-col v-for="(item, idx) in menus" :key="idx" :span="2">
          <div class="grid-content bg-purple">
            <el-select v-model="item.permission_flag" :disabled="isHidden" placeholder="请选择权限" @change="changeSelect(item)">
              <el-option label="全部权限" :value="2" />
              <el-option label="查看权限" :value="1" />
              <el-option label="无权限使用" :value="0" />
            </el-select>
          </div>
        </el-col>
      </el-row>
    </template>
  </base-content>
</template>

<script>
import { mapGetters } from 'vuex'
import { hasPermission } from '@/utils'
import { system } from '@/utils/config'
import { getAllMenuList, updateUserMenuDetail } from '@/api/authority'

export default {
  data() {
    const isHidden = !hasPermission('权限管理')
    return {
      list: [],
      system: system,
      isHidden
    }
  },
  computed: {
    ...mapGetters(['sidebar']),
    routes() {
      return this.$router.options.routes
    }
  },
  async mounted() {
    // 获取权限列表
    const result = await getAllMenuList()
    if (result.code === '0') {
      const data = result.info.data
      const list = this.classify(data)
      this.list = list
    }
  },
  methods: {
    classify(arr) {
      const map = arr.reduce((result, item) => {
        result[item.account_type] = result[item.account_type] || []
        result[item.account_type].push(item)
        return result
      }, {})
      return Object.values(map)
    },
    // 切换权限
    async changeSelect(row) {
      const { id, permission_flag } = row
      const result = await updateUserMenuDetail([{ id, permission_flag }])
      if (result.code === '0') {
        this.$message.success('权限更新成功')
      } else {
        this.$message.error(`权限更新失败：${result.msg}`)
      }
    }
  }
}
</script>
<style scoped>
  .el-row{
    line-height: 30px;
    text-align: center;
    margin-top: 20px;
    border-bottom: 1px solid #EBEEF5;
  }
  .bg-purple{
    margin-bottom: 20px;
  }
  .header{
    margin-bottom: 20px;
  }
</style>
